package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.pojo.Menu;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Override
    public List<Menu> findMenuList(String username) {
        List<Menu> parentMenuList = menuDao.findParentMenuByUserName(username);
        for (Menu menu : parentMenuList) {
            Integer id = menu.getId();
            List<Menu> chileMenuList = menuDao.findChildMenuListByParentId(id,username);
            menu.setChildren(chileMenuList);
        }
        System.out.println(parentMenuList);
        return parentMenuList;
    }


    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();     //每页长度
        Integer currentPage = queryPageBean.getCurrentPage(); //当前页
        PageHelper.startPage(currentPage,pageSize);//分页插件封装
        Page<Menu> page =menuDao.queryByCondition(queryString);
        long total = page.getTotal();
        List<Menu> result = page.getResult();
        return new PageResult(total,result);
    }
    //添加菜单项
    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }
    //编辑前查询
    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }
    //编辑菜单项
    @Override
    public void update(Menu menu) {
        menuDao.update(menu);
    }
    //删除菜单项
    @Override
    public void delete(Integer id) {
        // 在service层进行逻辑处理
        long count = menuDao.findCountByCheckItemId(id);
        if (count > 0){
            throw new RuntimeException("已关联角色,不能删除!");
        }else {
            menuDao.delete(id);
        }
    }

    @Override
    public List<Menu> findChildren(Integer id) {
        return menuDao.findChildren(id);
    }
    //查询所有

    public List<Menu> findAll() {
        return menuDao.findAll();
    }
}
